# encoding: utf-8
require "logstash/filters/base"
# This  filter will replace the contents of the default
# message field with whatever you specify in the configuration.
#
# It is only intended to be used as an .
class LogStash::Filters::Ip2location < LogStash::Filters::Base

  # Setting the config_name here is required. This is how you
  # configure this filter from your Logstash config.
  #
  # filter {
  #    {
  #     message => "My message..."
  #   }
  # }
  #
  config_name "ip2location"

  # Replace the message with this value.
  config :message, :validate => :string, :default => "Hello World!"
  
  config :ip_field, :validate => :string, :default => "127.0.0.1"
  config :ip_command, :validate => :string, :default => ""
  config :country, :validate => :string, :default => ""
  config :province, :validate => :string, :default => ""
  config :city, :validate => :string, :default => ""
  config :isp, :validate => :string, :default => ""


  config :ipinfo, :validate => :string, :default => ""
  
  @logger =self.logger
  public
  def register
    # Add instance variables
	@logger.info("ip_field is #{@ip_field},command is #{@ip_command}")
  end # def register

  public
  def filter(event)

    _ip = event.get("#{@ip_field}")
    _shell = @ip_command
    #_ip = '183.88.22.6'
    #_shell = 'python /opt/third-party/ip2region/searchip.py'
	#_res = `/opt/third-party/ip2region/ip.sh 180.110.50.103`
	
	_res = `#{_shell} #{_ip}`
	_infos=_res.gsub("\n","").split(" ")
	event.set("country", _infos[0])
	event.set("province", _infos[1])
	event.set("city", _infos[2])
	event.set("isp", _infos[3])	
	
	#event.set("country", _ip)
	#event.set("province", _shell)

	
	#stdin, stdout, stderr = Open3.popen3('python /opt/third-party/ip2region/searchip.py 180.110.50.103')
	#stdin.puts('')
	#_res = stdout.gets
	#event.set("ipinfo", _res.force_encoding("UTF-8"))
    filter_matched(event)
  end # def filter
end # class LogStash::Filters::Ip2location
